package com.qxp.simplerpc;

import com.qxp.simplerpc.connect.RpcClientHandler;
import com.qxp.simplerpc.entity.CommonProperties;
import com.qxp.simplerpc.entity.Registry;
import com.qxp.simplerpc.exception.RpcException;
import com.qxp.simplerpc.parse.URLParse;
import com.qxp.simplerpc.utils.SimpleRpcProperties;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Random;

public abstract class AbstractRegistryService implements RegistryService{
    // 注册中心地址
    protected String address;
    // 连接注册中心的超时时间
    protected int timeout;
    // 注册中心集群名称
    protected String clustername;
    // 节点名称
    protected String nodeName;
    // 配置类
    protected SimpleRpcProperties simpleRpcProperties;
    // 配置信息初始化
    protected void initRegisterProperties() {
        Registry registry = simpleRpcProperties.getRegistry();
        address = registry.getAddress();
        timeout = registry.getTimeout();
        clustername = registry.getClustername();
        nodeName = registry.getName();
        check();
    }
    // default
    protected void check() {
        // security check
        if (StringUtils.isEmpty(address)) {
            throw new RpcException("register center address can't be null...");
        }
        if (timeout == 0) {
            timeout = Integer.MAX_VALUE;
        }
        if (StringUtils.isEmpty(clustername)) {
            clustername = "/com.qxp.simplerpc";
        }else if(!clustername.contains("/")){
            clustername = "/" + clustername;
        }
        if (StringUtils.isEmpty(nodeName)) {
            nodeName = "data";
        }
    }

    private String getRegisterAddress(List<String> serverUrlList) {
        if (CollectionUtils.isEmpty(serverUrlList)) {
            return null;
        }
        //这里我们随机获取一个ip端口使用
        int index = new Random().nextInt(serverUrlList.size());
        return serverUrlList.get(index);
    }

    protected void doSubscribe(RpcClientHandler rpcClientHandler){
        // 选择策略====
        // 获取注册中心服务的地址
        String address = getRegisterAddress(listUrl());
        //(String)result.get(keyFormat(redisKey,registryName));
        // 比较获取的地址和当前的客户端的连接是否相同
        CommonProperties commonProperties = new CommonProperties();
        commonProperties.setHost(rpcClientHandler.getRpcClient().getHost());
        commonProperties.setPort(rpcClientHandler.getRpcClient().getPort());

        if (!commonProperties.toString().equals(address)) {
            commonProperties = URLParse.parseURL(address);
            // 重新定位服务器地址
            rpcClientHandler.getRpcClient().setHost(commonProperties.getHost());
            rpcClientHandler.getRpcClient().setPort(commonProperties.getPort());
            // 关闭
            if (!Objects.isNull(rpcClientHandler.getCtx())) {
                rpcClientHandler.getCtx().close();
            }
            new Thread(rpcClientHandler.getRpcClient()).start();
        }
    }

    protected String stringFormatWithSplit(String...str){
        List<String> stringList = Arrays.asList(str);
        StringBuilder stringBuilder = new StringBuilder();
        stringList.forEach(s -> {
            stringBuilder.append(s).append("/");
        });
        return stringBuilder.substring(0,stringBuilder.length() - 1);
    }


    protected abstract void doRegister(String url);
}
